<?php
/**
 * 地址相关服务
 * User: poptser@foxmail.com
 * Date: 2018/1/23
 * Time: 11:59
 */

namespace App\Services\Address;

use App\Repositories\Address\DeliverRegionCoordinatesRepositoryEloquent;
use App\Repositories\Address\DeliverRegionRepositoryEloquent;
use App\Repositories\Address\RegionRepositoryEloquent;
use App\Repositories\Address\UserAddressRepositoryEloquent;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class AddressService{
    //protected $DeliveryAreaService;
    protected $addressRepository;
    protected $regionRepository;

    public $userId;

    public function __construct(//DeliveryAreaService $deliveryAreaService ,
        UserAddressRepositoryEloquent $addressRepository,
        RegionRepositoryEloquent $regionRepository){
        $this->addressRepository = $addressRepository;
        $this->regionRepository = $regionRepository;

        //$this->DeliveryAreaService = $deliveryAreaService;

        //$this->userId = Auth::user()->user_id;
        $this->userId = 1;

    }

    /**
     * 获取用户默认地址
     * @return bool|mixed
     */
    public function getDefaultAddress(){
        $address_info = $this->addressRepository->getDefaultAddress($this->userId);
        //return $address_info;
        $address_info = $address_info[0];
        if($address_info){
            $address_info['province'] =  $this->regionRepository->idToString($address_info['province'],1);
            $address_info['city'] =  $this->regionRepository->idToString($address_info['city'],2);
            $address_info['district'] =  $this->regionRepository->idToString($address_info['district'],3);
            return $address_info;
        }else{
            return false;
        }
    }
    /**
     * 根据一个地址ID获取一个地址详情
     * @param int $address_id
     * @return bool|mixed
     */
    public function getAddress(int $address_id){
        $address_info = $this->addressRepository->getAddressById($address_id);
        if($address_info){

            $address_info['province'] =  $this->regionRepository->idToString($address_info['province'],1);
            $address_info['city'] =  $this->regionRepository->idToString($address_info['city'],2);
            $address_info['district'] =  $this->regionRepository->idToString($address_info['district'],3);

            return $address_info;
        }else{
            return false;
        }
    }

    /**
     * 获取用户地址列表
     * @param int $page_size
     * @return mixed
     * @throws \Prettus\Repository\Exceptions\RepositoryException
     */
    public function getAddressList(int $page_size = 1){
        $address_list = $this->addressRepository->getAddressList($this->userId,$page_size);

        $longitudeAndLatitude = [];
        foreach ($address_list as $key=>$value){

            $longitude_repair = $this->checkAddressRepair($value['sign_building'],$value['district_id']);
            //组装经纬度数组
            if($longitude_repair){
                $longitudeAndLatitude[] = $longitude_repair;
            }else{
                $longitudeAndLatitude[] = $this->repairLongitudeAndLatitude($value);
            }

            $address_list[$key]['province'] =  $this->regionRepository->idToString($value['province'],1);
            $address_list[$key]['city'] =  $this->regionRepository->idToString($value['city'],2);
            $address_list[$key]['district'] =  $this->regionRepository->idToString($value['district'],3);
        }
//        //批量查询
//        if(count($longitudeAndLatitude)>0){
//            $addressDelivery = $this->DeliveryAreaService->getDeliveryAreaByLongitudeAndLatitudeList(
//                $longitudeAndLatitude);
//            foreach ($address_list as $key=>$value){
//                $address_list[$key]['fac'] = $addressDelivery[$key];
//            }
//        }
        return $address_list;
    }


    /**
     * 修正经纬度混乱问题
     * @param array $longitudeAndLatitude
     * @return array
     */
    public function repairLongitudeAndLatitude(array $longitudeAndLatitude){
        if($longitudeAndLatitude['longitude']>$longitudeAndLatitude['latitude']){
            return ['longitude'=>$longitudeAndLatitude['longitude'],
                'latitude'=>$longitudeAndLatitude['latitude']];
        }else{
            return ['longitude'=>$longitudeAndLatitude['latitude'],
                'latitude'=>$longitudeAndLatitude['longitude']];
        }
    }

    /**
     * 检查经纬度是否纠错，并返回新的经纬度
     * @param string $signBuilding
     * @param int $districtId
     * @return array|bool
     */
    public function checkAddressRepair(string $signBuilding, int $districtId){
        $longitude_repair =  DB::table("landmark_repair")
            ->where([
                ['name','=',$signBuilding],
                ['district_id','=',$districtId],
                ['lng','<>',0]
            ])
            ->first(['lat','lng']);
        if($longitude_repair){
            return ['longitude'=>$longitude_repair['lng'],
                'latitude'=>$longitude_repair['lat']];
        }else{
            return false;
        }
    }

    /**
     * 地址转换经纬度 【 高德Api 】
     * @param string $address
     * @param string $city
     * @return mixed
     */
    public function addressToGps(string $address, string $city = '广州'){
        //高德版
        if(empty($city)){
            $city="广州";
        }
        $url = config('address.AMAP_URL')."key=".config('address.AMAP_KEY')."&city=".$city."&address=".$address;
        $get_data = file_get_contents($url);
        $Json_Data = json_decode($get_data, true);

        $location = $Json_Data['geocodes'][0]['location'];
        $location_array = explode(",",$location);
        $data['longitude'] = $location_array[0];    //经度
        $data['latitude'] = $location_array[1];     //纬度
        return $data;
    }

    /**
     * 新加地址
     * @param array $addressInfo
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    public function addAddress(array $addressInfo){
        $addressInfo['province'] =  $this->regionRepository->stringToId($addressInfo['province'],1);
        $addressInfo['city'] =  $this->regionRepository->stringToId($addressInfo['city'],2);
        $addressInfo['district'] =  $this->regionRepository->stringToId($addressInfo['district'],3);
        $this->addressRepository->addAddress($addressInfo);
    }

    /**
     * 更新地址
     * @param array $addressInfo
     * @param int $addressId
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    public function updateAddress(array $addressInfo, int $addressId){
        $this->addressRepository->update($addressInfo,$addressId);
    }

    /**
     * 删除地址
     * @param int $addressId
     */
    public function deleteAddress(int $addressId){
        $this->addressRepository->deleteAddress($addressId);
    }

    /**
     * 设置默认地址
     * @param int $addressId
     */
    public function setDefaultAddress(int $addressId){
        $this->addressRepository->setDefaultAddress($addressId,$this->userId);
    }


    /**
     * 自动补全地址
     * @param string $landmark 地标
     * @param string $city  所在城市
     * @return array
     */
    public function addressAutoComplete(string $landmark, string $city = "广州"){
        $url = config("address.AMAP_CIMPLETE")."key=".config("address.AMAP_KEY")."&keywords=".$landmark."&type=&location=&city=".$city."&datatype=poi";
        $html = file_get_contents($url);
        $data = json_decode($html,true);
        if($data['status']==1){
            $data['data'] = $data['tips'];
            foreach ($data['data'] as $key=>$value){
                if(empty($value['address'])){
                    unset($data['data'][$key]);
                    continue;
                }
                $location = explode(",",$value['location']);
                $url_p = "http://restapi.amap.com/v3/geocode/regeo?key=".C("AMAP_KEY")."&location=$location[0],$location[1]&poitype=&radius=1000&extensions=all&batch=false&roadlevel=0";
                $html_p = file_get_contents($url_p);
                $data_p = json_decode($html_p,true);
                $province = $data_p['regeocode']['addressComponent']['province'];
                if($data_p['regeocode']['addressComponent']['city']){
                    $city = $data_p['regeocode']['addressComponent']['city'];
                }else{
                    $city = "";
                }
                if($data_p['regeocode']['addressComponent']['district']){
                    $district = $data_p['regeocode']['addressComponent']['district'];
                }else{
                    $district = "";
                }
                $data['data'][$key]['ad_info']=array(
                    "city"=>$city,
                    "district"=>$district,
                    "province"=>$province
                );
                $data['data'][$key]['title'] = $value['name'];
                $data['data'][$key]['province'] = $province;
                $data['data'][$key]['city'] = $city;
                $data['data'][$key]['district'] = $district;
                if(count($location)>1){
                    $data['data'][$key]['location'] = array(
                        "lat"=>$location[1],
                        "lng"=>$location[0]
                    );
                }else{
                    $data['data'][$key]['location'] = null;
                }

                if(empty($value['id'])){
                    $data['data'][$key]['id'] = null;
                }

            }
            $new_data = array();
            foreach ($data['data'] as $key3=>$value3){
                $new_data[] = $value3;
            }
            return $new_data;
        }
    }
}